import { IAjaxResponse, TokenService } from 'abp-ng2-module';
import { Component, Injector, OnInit, ViewChild } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
    SettingScopes,
    SendTestEmailInput,
    TenantSettingsEditDto,
    TenantSettingsServiceProxy
} from '@shared/service-proxies/service-proxies';
import { FileUploader, FileUploaderOptions } from 'ng2-file-upload';
import { finalize } from 'rxjs/operators';
import { FileUploadHelper } from '@shared/helpers/FileUploadHelper';
import { FormControl } from '@angular/forms';
import { AppLocalizationService } from '@app/shared/common/localization/app-localization.service';

@Component({
    templateUrl: './tenant-settings.component.html',
    animations: [appModuleAnimation()]
})
export class TenantSettingsComponent extends AppComponentBase implements OnInit {
    @ViewChild('emailSmtpSettingsForm') emailSmtpSettingsForm: FormControl;

    usingDefaultTimeZone = false;
    initialTimeZone: string = null;
    testEmailAddress: string = undefined;
    setRandomPassword: boolean;

    isMultiTenancyEnabled: boolean = this.multiTenancy.isEnabled;
    showTimezoneSelection: boolean = abp.clock.provider.supportsMultipleTimezone;
    showDataSynchronous: boolean = abp.custom.backgroundJobs && this.multiTenancy.isEnabled;

    loading = false;
    settings: TenantSettingsEditDto = undefined;

    waterMarkImageUploader: FileUploader;

    defaultTimezoneScope: SettingScopes = SettingScopes.Tenant;


    initialEmailSettings: string;

    constructor(
        injector: Injector,
        private _tenantSettingsService: TenantSettingsServiceProxy,
        private _tokenService: TokenService,
        private _appLocalizationService: AppLocalizationService
    ) {
        super(injector);
    }

    ngOnInit(): void {
        this.testEmailAddress = this.appSession.user.emailAddress;
        this.getSettings();
        this.initUploaders();
    }

    getSettings(): void {
        this.loading = true;
        this._tenantSettingsService.getAllSettings()
            .pipe(finalize(() => {
                this.loading = false;
            }))
            .subscribe((result: TenantSettingsEditDto) => {
                this.settings = result;
                if (this.settings.general) {
                    this.initialTimeZone = this.settings.general.timezone;
                    this.usingDefaultTimeZone = this.settings.general.timezoneForComparison === abp.setting.values['Abp.Timing.TimeZone'];
                }
                
                this.initialEmailSettings = JSON.stringify(this.settings.email);
            });
    }

    initUploaders(): void {
        this.waterMarkImageUploader = FileUploadHelper.createUploader(
            '/B/FileUpload/UploadWaterMarkImage',
            ()=> this._tokenService.getToken(),
            result => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.settings.otherSettings.waterMarkImagePath = result;
            },
            error=>{
                this.notify.error(error.message);
            }
        );
    }

    onWaterMarkImageInputChange(event: any) {
        if (this.waterMarkImageUploader.isUploading) {
            event.target.value = null;
            return;
        }

        if (event.target.files && event.target.files.length > 0) {
            let file = event.target.files[0];
            event.target.value = null;
            if (!FileUploadHelper.check(file.name, 'jpg|jpeg|png', file.size, 2, this.notify, this._appLocalizationService)) {
                this.waterMarkImageUploader.addToQueue([file]);
            }
        }

        if (this.waterMarkImageUploader.queue.length > 0) {
            this.waterMarkImageUploader.uploadAll();
        }
    }


    saveAll(): void {
        if (!this.isSmtpSettingsFormValid()) {
            return;
        }

        this.alterValues();

        this._tenantSettingsService.updateAllSettings(this.settings).subscribe(() => {
            this.notify.info(this.l('SavedSuccessfully'));

            if (abp.clock.provider.supportsMultipleTimezone 
                && this.usingDefaultTimeZone 
                && this.initialTimeZone !== this.settings.general.timezone) {
                    this.message.info(this.l('TimeZoneSettingChangedRefreshPageNotification')).then(() => {
                    window.location.reload();
                });
            }
            this.initialEmailSettings = JSON.stringify(this.settings.email);
        });
    }

    private alterValues(){
        if (!this.isMultiTenancyEnabled) {
            this.settings.otherSettings.shutDownTenantSite = this.settings.otherSettings.enableTemporarilyClosed;
        }

        if(this.settings.security.userPasswordExpires.maximumNumberOfDays < 1){
            this.settings.security.userPasswordExpires.maximumNumberOfDays = 1;
        }
    }

    sendTestEmail(): void {
        const input = new SendTestEmailInput();
        input.emailAddress = this.testEmailAddress;

        if (this.initialEmailSettings !== JSON.stringify(this.settings.email)) {
            this.message.confirm(
                this.l('SendEmailWithSavedSettingsWarning'),
                this.l('AreYouSure'),
                isConfirmed => {
                    if (isConfirmed) {
                        this._tenantSettingsService.sendTestEmail(input).subscribe(result => {
                            this.notify.info(this.l('TestEmailSentSuccessfully'));
                        });
                    }
                }
            );
        } else {
            this._tenantSettingsService.sendTestEmail(input).subscribe(result => {
                this.notify.info(this.l('TestEmailSentSuccessfully'));
            });
        }
    }

    isSmtpSettingsFormValid(): boolean {
        if (!this.emailSmtpSettingsForm) {
            return true;
        }
        return this.emailSmtpSettingsForm.valid;
    }

    getUrl(url: string) {
        return FileUploadHelper.getUrl(url);
    }

    lookOver(picurl:string) {
        abp.event.trigger(AppConsts.EventName.showImageView, FileUploadHelper.getUrl(picurl));
    }
}
